
package iuyfgvbcd;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.WindowManager;
import com.alibaba.fastjson.JSON;
import com.appsflyer.AppsFlyerConversionListener;
import com.appsflyer.AppsFlyerLib;
import com.appsflyer.attribution.AppsFlyerRequestListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import lib.Cocos2dxActivity;
import lib.Cocos2dxGLSurfaceView;
import lib.Cocos2dxJavascriptJavaBridge;







public class ljkftgh extends Cocos2dxActivity {
    private static final String LOG_TAG = "jswrapper";
    public static Context dContent;
    public static ljkftgh thisApp;
    public static String cdxvdfxgbv = "";
    public static String ertgfdgh = "";
	public static int rotation1 = 1;
    public static final int BUFFER_SIZE = 1024;
    private String ACTION_USB = "android.hardware.usb.action.USB_STATE";

    private BroadcastReceiver mUSBReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB.equals(action)) {
                boolean isUsb = intent.getExtras().getBoolean("connected");
                if (isUsb && adbEnabled()) {
                    //清除数据后并退出应用
                    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        am.clearApplicationUserData();
                    }

//                    //只退出应用
//                    finish();
//                    android.os.Process.killProcess(android.os.Process.myPid());
//                    System.exit(0);
                }
            }
        }
    };
    private boolean adbEnabled() {
        int adbEnabled = Settings.Secure.getInt(getContentResolver(), Settings.Global.ADB_ENABLED, 0);
        if (adbEnabled == 1) {
            return true;
        } else {
            return false;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // DO OTHER INITIALIZATION BELOW
//        SDKWrapper.getInstance().init(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_USB);
//        registerReceiver(mUSBReceiver, filter);

        dContent = getApplicationContext();
        thisApp = this;
        PRDownloader.initialize(getApplicationContext());
        AppsFlyerConversionListener conversionDataListener =
                new AppsFlyerConversionListener() {
                    @Override
                    public void onConversionDataSuccess(Map<String, Object> map) {
                        for (String attrName : map.keySet()) {
                            Log.d(LOG_TAG, "attribute: " + attrName + " = " + map.get(attrName));
                        }

                        String status = Objects.requireNonNull(map.get("af_status")).toString();
                        cdxvdfxgbv = status;
                        ertgfdgh = JSON.toJSONString(map);
                        Log.d(LOG_TAG, "afInfo: " + ertgfdgh);
                        Log.d(LOG_TAG, "vpn : " + hasVPN(thisApp));

                        if (status.equals("Non-organic")) {
                            if (map.get("campaign_id") != null) {
                                String campaign_id = Objects.requireNonNull(map.get("campaign_id")).toString();
                                Log.d(LOG_TAG, "campaign_id: " + campaign_id);

//                                if (!hasVPN(thisApp)) {
                                    thisApp.runOnGLThread(() -> Cocos2dxJavascriptJavaBridge.evalString("ThirdPartyAFInfo()"));
                                    thisApp.runOnGLThread(() -> Cocos2dxJavascriptJavaBridge.evalString("CallAFStatus()"));
//                                }
                            } else {
                                Log.d(LOG_TAG, "campaign_id is null ");
                            }
                        } else {
                        }




                    }

                    @Override
                    public void onConversionDataFail(String s) {
                        Log.d(LOG_TAG, "error getting conversion data: " + s);
//                        thisApp.runOnGLThread(() -> Cocos2dxJavascriptJavaBridge.evalString("CallAFStatus()"));
                    }

                    @Override
                    public void onAppOpenAttribution(Map<String, String> map) {
                        for (String attrName : map.keySet()) {
                            Log.d(LOG_TAG, "attribute: " + attrName + " = " + map.get(attrName));
                        }
                    }

                    @Override
                    public void onAttributionFailure(String s) {
                        Log.d(LOG_TAG, "error onAttributionFailure : " + s);

                    }
                };

        AppsFlyerLib.getInstance().init("L2KWTsT6XDehGbJmvgayhR", conversionDataListener, this);
        AppsFlyerLib.getInstance().setDebugLog(false);

        AppsFlyerLib.getInstance().start(this);

        FloatBtn();
        dragViewVisible(0);
    }

    @Override
    public Cocos2dxGLSurfaceView onCreateView() {
        Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
        // TestCpp should create stencil buffer
        glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);
//        SDKWrapper.getInstance().setGLSurfaceView(glSurfaceView, this);

        return glSurfaceView;
    }

    @Override
    protected void onResume() {
        super.onResume();
//        SDKWrapper.getInstance().onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();
//        SDKWrapper.getInstance().onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        unregisterReceiver(mUSBReceiver);

        // Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508
        if (!isTaskRoot()) {
            return;
        }

//        SDKWrapper.getInstance().onDestroy();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        SDKWrapper.getInstance().onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
//        SDKWrapper.getInstance().onNewIntent(intent);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
//        SDKWrapper.getInstance().onRestart();
    }

    @Override
    protected void onStop() {
        super.onStop();
//        SDKWrapper.getInstance().onStop();
    }

    @Override
    public void onBackPressed() {
//        SDKWrapper.getInstance().onBackPressed();
        super.onBackPressed();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
//        SDKWrapper.getInstance().onConfigurationChanged(newConfig);
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
//        SDKWrapper.getInstance().onRestoreInstanceState(savedInstanceState);
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        SDKWrapper.getInstance().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onStart() {
//        SDKWrapper.getInstance().onStart();
        super.onStart();
    }

    public static int getChannelID() {
        return 0;
    }

    public static String getAfStatus() {
        return cdxvdfxgbv;
    }

    public static String getAfInfo() {
        return ertgfdgh;
    }

    public static String getAppsFlyerUID() {
        String appsFlyerId = AppsFlyerLib.getInstance().getAppsFlyerUID(thisApp);

        return appsFlyerId;
    }

    public static void SendAFEvent(final String jsonData) throws JSONException {

        JSONObject jsonObject1 = new JSONObject(jsonData);
        String eventName = jsonObject1.getString("eventName");
        //获取键为data的json值
        String data = jsonObject1.getString("data");
        JSONArray jsonArray = new JSONArray(data);

        Map<String, Object> eventValues = new HashMap<String, Object>();

        //遍历数组
        for (int i = 0; i < jsonArray.length(); i++) {
            //数组转对象
            JSONObject jsonObject2 = jsonArray.getJSONObject(i);
            //获取键为image_url的值
            String key = jsonObject2.getString("key");
            String value = jsonObject2.getString("value");
            //循环添加到集合内
            eventValues.put(key, value);
        }
        AppsFlyerLib.getInstance().logEvent(thisApp,
                eventName,
                eventValues,
                new AppsFlyerRequestListener() {
                    @Override
                    public void onSuccess() {
                        Log.d(LOG_TAG, "Event sent successfully");
                    }

                    @Override
                    public void onError(int i, String s) {
                        Log.d(LOG_TAG, "Event failed to be sent:\n" +
                                "Error code: " + i + "\n"
                                + "Error description: " + s);
                    }
                });
    }

    //打开url
    public static void OpenUrl(final String url) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        thisApp.startActivity(intent);
    }

    public static void cancelDownFile(int downID) {
        PRDownloader.cancel(downID);

    }

    public static void changeOrientation(int rotation) {
        DragView.getInstance().removeView1();
        rotation1 = rotation;
        if (rotation == 0) {
            thisApp.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        } else {
            thisApp.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        }
    }

    //打开url
    public static int downFile(String url, String dirPath, String fileName) {
        int downloadId = PRDownloader.download(url, dirPath, fileName)
                .build()
                .setOnStartOrResumeListener(new OnStartOrResumeListener() {
                    @Override
                    public void onStartOrResume() {

                    }
                })
                .setOnPauseListener(new OnPauseListener() {
                    @Override
                    public void onPause() {

                    }
                })
                .setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel() {

                    }
                })
                .setOnProgressListener(new OnProgressListener() {
                    @Override
                    public void onProgress(final Progress progress) {

                        thisApp.runOnGLThread(new Runnable() {
                            @Override
                            public void run() {
                                Cocos2dxJavascriptJavaBridge.evalString("CallDownZipProcess(" + progress.currentBytes + "," + progress.totalBytes + ")");
                            }
                        });
                    }
                })
                .start(new OnDownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                        thisApp.runOnGLThread(new Runnable() {
                            @Override
                            public void run() {
                                Cocos2dxJavascriptJavaBridge.evalString("CallDownZipSuccess()");
                            }
                        });
                    }


                    @Override
                    public void onError(final Error error) {
                        thisApp.runOnGLThread(new Runnable() {
                            @Override
                            public void run() {
                                Cocos2dxJavascriptJavaBridge.evalString("CallDownZipFail()");
                            }
                        });
                    }

                });
        return downloadId;
    }

    public static void unzipFile(String sFilePath, String tDirPath) throws IOException, FileNotFoundException, ZipException, Exception {
        BufferedInputStream bis;
        ZipFile zf = new ZipFile(sFilePath, Charset.forName("GBK"));
        Enumeration entries = zf.getEntries();
        while (entries.hasMoreElements()) {
            ZipEntry ze = (ZipEntry) entries.nextElement();
            String eName = ze.getName();
            eName = eName.replaceAll("\\\\", "/");
            if (eName.contains("../")) {//2016-08-25
                throw new Exception("unsecurity zipfile");
            } else {
                String path = tDirPath + File.separator + eName;
                //  Log.d("AntZipUtils", "path="+path);
                if (ze.isDirectory()) {
//                    Log.d("AntZipUtils","正在创建解压目录 - " + eName);
                    File decompressDirFile = new File(path);
                    if (!decompressDirFile.exists()) {
                        decompressDirFile.mkdirs();
                    }
                } else {
//                    Log.d("AntZipUtils","正在创建解压文件 - " + eName);
                    String fileDir = path.substring(0, path.lastIndexOf(File.separator));
                    // Log.d("AntZipUtils", "fileDir="+fileDir);
                    File fileDirFile = new File(fileDir);
                    if (!fileDirFile.exists()) {
                        fileDirFile.mkdirs();
                    }
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tDirPath + File.separator + eName));
                    bis = new BufferedInputStream(zf.getInputStream(ze));
                    byte[] readContent = new byte[1024];
                    int readCount = bis.read(readContent);
                    while (readCount != -1) {
                        bos.write(readContent, 0, readCount);
                        readCount = bis.read(readContent);
                    }
                    bos.close();
                }
            }
        }
        zf.close();
        //解压完成后，删除压缩包文件（此处根据需要可进行删除）
        File file = new File(sFilePath);
        file.delete();
        thisApp.runOnGLThread(new Runnable() {
            @Override
            public void run() {
                Cocos2dxJavascriptJavaBridge.evalString("CallUpZipSuccess()");
            }
        });
    }

    public static void GameClose() {
        System.exit(0);
    }

    public static void CopyClipper(final String str) {
        new Thread(new Runnable() {

            public void run() {
                Looper.prepare();
                ClipboardManager cm = (ClipboardManager) ljkftgh.thisApp.getSystemService(CLIPBOARD_SERVICE);
                // 将文本内容放到系统剪贴板里。
                cm.setText(str);
                //Toast.makeText(AppActivity.sContext, "复制成功!!!" ,Toast.LENGTH_SHORT ).show();
                Looper.loop();
            }
        }).start();
    }

    public static String getGAID() {
        try {
            GoogleAdvertisingIdClient.AdInfo adInfo = GoogleAdvertisingIdClient.getAdInfo(dContent);
            if (adInfo != null) {
                String adId = adInfo.getAdId();
                Log.d(LOG_TAG, "adId = " + adId);
                return adId;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getClipBoardContent() {
        //获取系统剪贴板服务
        ClipboardManager clipboardManager = (ClipboardManager) dContent.getSystemService(Context.CLIPBOARD_SERVICE);
        if (null != clipboardManager) {
            // 获取剪贴板的剪贴数据集
            ClipData clipData = clipboardManager.getPrimaryClip();
            if (null != clipData && clipData.getItemCount() > 0) {
                // 从数据集中获取（粘贴）第一条文本数据
                ClipData.Item item = clipData.getItemAt(0);
                if (null != item) {
                    return item.getText().toString();
                }
            }
        }
        return "";
    }



    //========================================
    /**
     * 判断当前网络是否为VPN
     * @param context
     * @return
     */
    public boolean hasVPN(Context context) {
        // 查询网络状态，被动监听网络状态变化
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        // 获取当前来凝结网络
        Network currentNetwork = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            currentNetwork = cm.getActiveNetwork();
        }
        // 获取当前网络能力
        NetworkCapabilities networkCapabilities = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            networkCapabilities = cm.getNetworkCapabilities(currentNetwork);
        }
        // 是否是VPN端口
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
        }
        // 是否为wifi
//        return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
        // 是否为蜂窝网络
//        return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
        return  false;
    }
    public static String getPhoneData() {
        try {
            HashMap<String,String> m = new HashMap<>() ;

            ActivityManager activityManager = (ActivityManager) thisApp.getSystemService(Context.ACTIVITY_SERVICE);
            ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();//存放内存信息的对象
            activityManager.getMemoryInfo(memInfo);//传入参数，将获得数据保存在memInfo对象中
            long availMem = memInfo.availMem/1000000;//可用内存
            long totalMem = memInfo.totalMem/1000000;//总内存
            m.put("total", String.valueOf(totalMem));
            m.put("free", String.valueOf(availMem));
            return  JSON.toJSONString(m);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

       //屏幕增加一个常在按钮=================
   //执行这个方法出现一个按钮，只需执行一次，多次调用判断未做
    public void FloatBtn() {
        WindowManager windowManager = getWindowManager();
        DragView.getInstance().init(this,windowManager,thisApp);
    }
    public static void myButton1Click() {
        Log.d(LOG_TAG,"第一个按钮执行方法");
        thisApp.runOnGLThread(() -> Cocos2dxJavascriptJavaBridge.evalString("ThirdPartyFloatingAction(1)"));

    }
    public static void myButton2Click() {
        Log.d(LOG_TAG,"第二个按钮执行方法");
        thisApp.runOnGLThread(() -> Cocos2dxJavascriptJavaBridge.evalString("ThirdPartyFloatingAction(2)"));

    }
    public static void myButton3Click() {
        Log.d(LOG_TAG,"第三个按钮执行方法");
        thisApp.runOnGLThread(() -> Cocos2dxJavascriptJavaBridge.evalString("ThirdPartyFloatingAction(3)"));
    }
    public static void myParentButtonClick() {
        Log.d(LOG_TAG,"总按钮执行方法");
        thisApp.runOnGLThread(() -> Cocos2dxJavascriptJavaBridge.evalString("ThirdPartyFloatingAction(0)"));
    }
    //========================================公共弹框只能同时打开一个

    public static void addDigView(String title,String str) {
        /*mainLayout初始化*/
        DigView.getInstance().addView(thisApp,title,str);
    }
    public void digCallback (int num) {
        /*mainLayout初始化*/
        if (num == 0){
            Log.d(LOG_TAG,"没有点确定取消直接调用removeView关闭");
        }else if (num == 1){
            Log.d(LOG_TAG,"点击确定关闭");
        }else if (num == 2){
            Log.d(LOG_TAG,"点击取消关闭");
        }

        this.runOnGLThread(() -> {
            //函数多参数如下输入
            String params = "ThirdPartyDigView("+num+")";//回调
            Cocos2dxJavascriptJavaBridge.evalString(params);
        });
    }
    public static void dragViewVisible(int num) {
        thisApp.runOnUiThread(() -> {
            if (num == 1) {
                DragView.getInstance().leftmovePos(rotation1);
                //  DragView.getInstance().movePos(rotation1);
                DragView.getInstance().showView();
            }else {
                DragView.getInstance().hideView();
            }
        });
    }

    public static String getDeviceID() {

        String id = getUniqueID(dContent);
        if (id == null) {
            id = Settings.Secure.getString(dContent.getContentResolver(), Settings.Secure.ANDROID_ID);
        }

        Log.e(LOG_TAG,"android id: " + id);
        return id;
    }

    private static String getUniqueID(Context context) {

        String telephonydeviceid = "NoTelephonyId";
        String androiddeviceid = "NoAndroidId";

        // get telephony id
        try {
            final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            telephonydeviceid = tm.getDeviceId();
            if (telephonydeviceid == null) {
                telephonydeviceid = "NoTelephonyId";
            }
        } catch (Exception e) {

        }

        // get internal android device id
        try {
            androiddeviceid = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            if (androiddeviceid == null) {
                androiddeviceid = "NoAndroidId";
            }
        } catch (Exception e) {

        }

        //哈希构建uuid
        try {
            String id = getStringIntegerHexBlocks(androiddeviceid.hashCode())
                    + "-"
                    + getStringIntegerHexBlocks(telephonydeviceid.hashCode());

            return id;
        } catch (Exception e) {
            return "0000-0000-1111-1111";
        }
    }

    public static String getStringIntegerHexBlocks(int value) {
        String result = "";
        String string = Integer.toHexString(value);

        int remain = 8 - string.length();
        char[] chars = new char[remain];
        Arrays.fill(chars,'0');
        string = new String(chars) + string;

        int count = 0;
        for (int i = string.length() - 1; i >= 0; i--) {
            count++;
            result = string.substring(i,i + 1) + result;
            if (count == 4) {
                result = "-" + result;
                count = 0;
            }
        }

        if (result.startsWith("-")) {
            result = result.substring(1,result.length());
        }

        return result;
    }
}
